<template>
  <div class="p-6px">
    <!-- 搜索条件 -->
    <el-form v-show="showSearch" :inline="true" @submit.prevent>
      <el-form-item label="规则名称" prop="name">
        <el-input placeholder="请输入规则名称" v-model="searchParams.name" clearable style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
        <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格头部按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5" v-auth="['system:role:add']">
        <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
      </el-col>
      <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
    </el-row>

    <br />
    <!-- 数据表格 -->
    <el-table
      max-height="520px"
      v-loading="loading"
      v-adaptive
      border
      :data="tableList"
      empty-text="暂时没有数据哟"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" prop="id" width="120px" align="center" type="index"></el-table-column>
      <el-table-column
        label="规则名称"
        prop="name"
        width="120px"
        :show-overflow-tooltip="true"
        align="center"
      ></el-table-column>
      <el-table-column label="回复类型" prop="content_type" width="200px" align="center"></el-table-column>
      <el-table-column label="启用状态" prop="status" width="100px" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
            :inline-prompt="true"
            @change="handleSwitch(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="回复内容" prop="content" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="created_at" align="center"></el-table-column>
      <el-table-column label="操作" align="left" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
            修改
          </el-button>
          <el-button type="danger" size="small" plain @click="handleDelete(row)" v-auth="['system:role:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <br />
    <!-- 分页 -->
    <el-pagination
      background
      v-model:current-page="searchParams.pageNo"
      v-model:page-size="searchParams.pageSize"
      v-show="total > 0"
      :page-sizes="[10, 20, 50, 100, 200]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleListPage"
      @current-change="handleListPage"
    />

    <!-- 添加 OR 修改 -->
    <KoiDialog
      ref="koiDialogRef"
      :title="title"
      @koi-confirm="handleConfirm"
      @koi-cancel="handleCancel"
      :loading="confirmLoading"
    >
      <template #content>
        <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
          <el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
              <el-form-item label="角色编号" prop="roleCode">
                <el-input v-model="form.roleCode" placeholder="请输入角色编号" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
              <el-form-item label="角色状态" prop="roleStatus">
                <el-select v-model="form.roleStatus" placeholder="请选择角色状态" style="width: 260px" clearable>
                  <el-option label="启用" value="0" />
                  <el-option label="停用" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
              <el-form-item label="角色排序" prop="sorted">
                <el-input-number v-model="form.sorted" style="width: 260px" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
              <el-form-item label="角色备注" prop="remark">
                <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入角色备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </KoiDialog>

  </div>
</template>

<script setup lang="ts" name="rolePage">
import { ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox } from "@/utils/koi.ts";
import { listPage, read, add, update, changeStatus } from "@/plugin/colewechat/api/reply/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  reply_type: "text",
  name: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: "",
    reply_type: "text"
  };
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    console.log("角色数据表格数据->", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    console.log("表格数据->>>>>>>>>>>>>>>", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});
const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  ids.value = selection.map((item: any) => item.roleId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "角色添加";
  form.value.status = "0";
  koiDialogRef.value.koiOpen();
  koiNoticeSuccess("添加");
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await read(id);
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据获取失败，请刷新重试");
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "角色修改";
  const roleId = row ? row.roleId : ids.value[0];
  if (roleId == null || roleId == "") {
    koiMsgError("请选择需要修改的数据");
  }
  console.log(roleId);
  // 回显数据
  handleEcho(roleId);
  koiDialogRef.value.koiOpen();
  koiNoticeSuccess("修改");
};

/** 添加 AND 修改弹出框 */
const koiDialogRef = ref();
// 标题
const title = ref("角色管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  roleId: null,
  roleName: null,
  roleCode: null,
  status: null,
  sorted: 1,
  remark: null
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    roleId: null,
    roleName: null,
    roleCode: null,
    status: null,
    sorted: 1,
    remark: null
  };
};

/** 表单规则 */
const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名字", trigger: "null" }],
  roleCode: [{ required: true, message: "请输入角色编号", trigger: "null" }],
  roleStatus: [{ required: true, message: "请输入选择角色状态", trigger: "null" }],
  sorted: [{ required: true, message: "请输入排序号", trigger: "null" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      // 后端API-[第一种：async await]
      // try{
      //   // 添加或者修改接口
      //   await addRole(form);
      // }catch(error){
      //    console.log(error);
      // }

      // 后端API-[第二种：then]
      // addRole(form).then(() => {
      //   // 一定是成功的
      // }).catch(error => {
      //   console.log(error);
      // })

      console.log("表单ID", form.value.roleId);
      if (form.value.roleId != null && form.value.roleId != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 状态switch */
const handleSwitch = (row: any) => {
  let text = row.status == 0 ? "启用" : "停用";
  koiMsgBox("确认要[" + text + "]-[" + row.name + "]吗？")
    .then(async () => {
      resetForm();
      if (!row.id) {
        koiMsgWarning("请选择需要修改的数据");
        return;
      }
      try {
        await changeStatus(row.id, row.status);
        koiNoticeSuccess("修改成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("修改失败，请刷新重试");
      }
    })
    .catch(() => {
      console.log(`xxx`);
      handleTableData();
    });
};

/** 删除 */
const handleDelete = (row: any) => {
  if (row.id == null || row.id == "") {
    koiMsgWarning("请选中需要删除的数据");
  }
  koiMsgBox("您确认需要删除[" + row.name + "]么？")
    .then(async () => {
      try {
        await changeStatus(row.id, -1);
        koiNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("删除失败，请刷新重试");
      } finally {
        handleTableData();
      }
    })
    .catch(() => {
      // koiMsgError("已取消");
    });
};

</script>

<style lang="scss" scoped></style>
